<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" prop="crateDate">
        <el-date-picker clearable
          v-model="queryParams.crateDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上传时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option
            v-for="dict in dict.type.res_file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属的用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入所属的用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_show_hide"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table
      :data="organizaDataList"
      row-key="id"
      border
      style="width: 100%;"
      :cell-style="columnStyle"
      :header-cell-style="headerStyle">
      <el-table-column
        v-for="(item,index) in organizaColumns"
        :key="index"
        :label="item.label"
        :prop="item.props"
        :width="item.width"
      >
        <template slot-scope="scope">
          <span v-if="index!=8">{{JudgmentData(scope.row[item.props])?scope.row[item.props]: '-'}}</span>
          <span v-else>{{scope.row[item.props]==1?"显示":"隐藏"}}</span>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="240"
        label="操作">

          <template v-slot="scope">

                      <a :href="scope.row.httpPath" download v-if="!scope.row.folder"><i class="el-icon-download"></i>下载</a>
                      <el-button
                        v-if="!scope.row.folder"
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['res:info:remove']"
                      >删除</el-button>

                      <!-- 分享文件对话框 -->
                      <el-button v-show="scope.row.state" type="text" @click="share(scope.row.id,scope.row.httpPath)" v-if="!scope.row.folder">分享</el-button>
                      <el-button v-show="scope.row.state" type="text" @click="createNewFolder(scope.row.id)" v-if="scope.row.folder">新建文件夹</el-button>
                      <el-button v-show="scope.row.state" type="text" @click="createNewFile(scope.row.id)" v-if="scope.row.folder">添加文件</el-button>

                    </template>

      </el-table-column>
    </el-table>

<!-- 获取分享链接 -->
    <el-dialog title="文件分享" :visible.sync="showDialog">
      <add-share-edit v-if="showDialog" @close-dialog="changeShowDialog" :file-id="fileId" :http-path="httpPath"></add-share-edit>
    </el-dialog>

    <el-dialog title="新建文件夹" :visible.sync="showDialog1">
      <add-folder-edit v-if="showDialog1" @close-dialog1="changeShowDialog1" :parent-id="parentId" ></add-folder-edit>
    </el-dialog>
    <el-dialog title="添加文件" :visible.sync="showDialog2">
      <add-file-edit v-if="showDialog2" @close-dialog2="changeShowDialog2" :parent-id="parentId" ></add-file-edit>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo ,getFolderList,querylist } from "@/api/resource/info";
import {getToken} from "@/utils/auth";
import AddShareEdit from "./Edit/AddShareEdit";
import { isNull,treeDataTranslate } from "../../../utils/indexTree";
import AddFolderEdit from "./Edit/AddFolderEdit";
import AddFileEdit from "./Edit/AddFileEdit";

export default {
  name: "Info",
  components: {AddShareEdit,AddFolderEdit,AddFileEdit},
  dicts: ['res_file_folder', 'res_file_type', 'sys_show_hide'],
  data() {
    return {
      showDialog2: false,
      showDialog1: false,
      parentId: 0,
      menuList: [],
      formFolder: {},
      props: {
        value: "id",
        label:  "fileName",
        children: "children"
      },
      organizaDataList: [],
      value: true,
      organizaColumns: [
        { label: "文件名", props: "fileName", width: "" },
        { label: "上传时间", props: "crateDate", width: "" },
        { label: "文件大小",props: "fileSize", width: ""},
        { label: "文件类型", props: "fileType", width: "" },
        { label: "是否为文件夹", props: "folder", width: "" },
        { label: "用户名", props: "userName", width: "" },
        { label: "秒传", props: "md5", width: "" },
        { label: "网络路径", props: "httpPath", width: "" },
        { label: "状态", props: "state", width: "" },
        { label: "文件类型", props: "parentId", width: "" },
      ],
      id:0,
      fileId: 0,
      httpPath: "",
      showDialog: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      // open: false,
      // 查询参数
      queryParams: {
        fileName: null,
        crateDate: null,
        fileSize: null,
        fileType: null,
        filePath: null,
        userId: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      imageUrl:"",
      fileList: [],
      headers:{
        "Authorization":""
      },
    };
  },
  created() {
    this.getList();
    this.headers.Authorization = getToken();
    this.getFolder()

  },
  methods: {
    createNewFile(val) {
      this.parentId = val;
      this.showDialog2  = true;
    },
    changeShowDialog2() {
      this.showDialog2 = false;
      this.getList();
    },
    changeShowDialog1(){
      this.showDialog1 = false;
      this.getFolder();
      this.getList();
    },
    createNewFolder(id){
      this.parentId = id;
      this.showDialog1 = true;
    },
    getFolder() {
      getFolderList().then(response => {
        let  a = new Array();
        a = response.rows;
        console.log(a)
        this.menuList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getValue(val) {
      this.formFolder.parentId = val;
    },
    // 更改单元格样式
    columnStyle() {
      return {
        height: "40px",
        'padding': '0px',
        'text-align': 'center',
      };
    },
    // 更改表头单元格样式
    headerStyle() {
      return {
        height: "45px",
        'background': '#EEF4FF',
        'padding': '0px',
        'text-align': 'center',
        'color': '#333333',
        'font-size': '14px',
        'font-weight': 400,
      };
    },
    // 树形数据转换
    changeData() {
      this.organizaDataList = treeDataTranslate( this.organizaDataList, 'id')
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    switchChange(row){
      updateInfo(row).then(response=>{

      })
    },
    secondsPass() {
      const file = new FileReader();

    },
    share(id,httpPath) {
      this.fileId = id;
      this.httpPath = httpPath;
      this.showDialog = true;
    },
    changeShowDialog (val) {
      this.showDialog = val;
    },
    open() {
      this.$prompt('请输入邮箱', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: '邮箱格式不正确'
      }).then(({ value }) => {
        this.$message({
          type: 'success',
          message: '你的邮箱是: ' + value
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });


    },
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.organizaDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleChange(file,fileList) {
      console.log(file.raw)
      this.imageUrl = URL.createObjectURL(file.raw)
      const reader = new FileReader();
      reader.onload=function(e){
        const text=reader.result;
      };
      const red =  reader.readAsText(file.raw);
      console.log(red)
    },

    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fileName: null,
        crateDate: null,
        fileSize: null,
        fileType: null,
        filePath: null,
        folder: null,
        userId: null,
        md5: null,
        httpPath: null,
        state: null,
        parentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.state!=null){
        if (this.queryParams.state==0){
          this.queryParams.state = 1;
        }else {
          this.queryParams.state = 0;
        }
      }
     querylist(this.queryParams).then(response=>{
       this.organizaDataList = response.rows;
     });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件";
    },
    /** 分享按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "分享文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文件编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('res/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  },
  computed: {
    JudgmentData() {
      return (data)=>{
        let status = !isNull(data)
        return status
      }
    }
  },
};


</script>
<style>
.download {
  width: 20px;
  height: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
